<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <table border="1">
        <thead>
            <tr>
                <th>编号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>性别</th>
                <th>操作</th>
            </tr>
        </thead>
        <tbody id="list"></tbody>
    </table>

    <script>
        let studentsData = [
            { id: 1, name: '张三', age: 20, gender: '男' },
            { id: 2, name: '李四', age: 20, gender: '男' },
            { id: 3, name: '王五', age: 20, gender: '男' },
        ];

        render();


        list.onclick = function (e) {
            if (e.target.className === 'deleteBtn') {
                // 获取当前按钮所对应i或id
                // const i = e.target.getAttribute("data-i");
                // const id = e.target.getAttribute("data-id");

                const i = e.target.dataset.i;
                const id = e.target.dataset.id;

                // 通过下标删除
                // studentsData.splice(i, 1);

                // 通过id删除
                // const index = studentsData.findIndex(item => item.id == id)
                // studentsData.splice(index, 1);

                studentsData = studentsData.filter(item => item.id != id);

                render();
            }
        }



        function render() {
            list.innerHTML = studentsData.map((item, index) => (
                `<tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.age}</td>
                <td>${item.gender}</td>
                <td>
                    <button class="deleteBtn" data-i="${index}" data-id="${item.id}">
                        删除
                    </button>
                    <button>修改</button>
                </td>
            </tr>`
            )).join("")
        }

    </script>
</body>

</html>